package com.二叉树2;



import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * Path Sum
 *
 * Solution
 * Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
 *
 * Note: A leaf is a node with no children.
 *
 * Example:
 *
 * Given the below binary tree and sum = 22,
 *
 *       5
 *      / \
 *     4   8
 *    /   / \
 *   11  13  4
 *  /  \      \
 * 7    2      1
 * return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
 */
public class 树的和 {
    static class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            Stack<TreeNode> stack = new Stack<>();
            TreeNode tmp = null; ;
            while (root != null || !stack.isEmpty()){
                 while (root != null){
                    sum -= root.val;
                    stack.push(root);
                    root  = root.left;
                }
                root = stack.peek();
                if(root.left == null && root.right == null && sum == 0){
                     return true;
                }
                if(root.right != null && root.right != tmp ){
                    root = root.right;
                }
                else{
                    sum += root.val;
                 tmp =   stack.pop();
                    root  = null;
                }
            }
            return false;
        }

        public boolean hasPathSum2(TreeNode root, int sum) {
            Stack<TreeNode> visitedNodes = new Stack<>();
            TreeNode prev = null;

            while(root!=null || !visitedNodes.isEmpty()){
                while(root!=null){
                    visitedNodes.push(root);
                    sum -= root.val;
                    prev = root;
                    root = root.left;
                }
                root = visitedNodes.peek();
                if(root.left==null && root.right == null && sum==0) return true;
                if(root.right != null && root.right != prev){
                    root = root.right;
                }else{
                    sum += root.val;
                     prev = visitedNodes.pop();
                    root = null;
                }
            }

            return false;
        }

        public static void main(String[] args) {
            Solution solution = new Solution();
            boolean flag = solution.hasPathSum(new TreeNode(new int[]{1,2,3,4,5,6,7}),10);
            Deque<TreeNode> deque ;

//            for(int i  = 1,j=2;i==1;){
//                System.out.println(i);
//            }
        }
    }
}
